<?php

use
    Formax\Paginator\QueryBuilder as Paginator;

class UserController extends ControllerBase
{
    public function initialize()
    {
        $this->i18n->import('auth');
    }

    public function loginAction()
    {
        $request = $this->request;

        if ($request->isAjax() && $request->isPost()) {
            try {
                $this->auth->login(
                    $request->getPost('username'),
                    $request->getPost('password'),
                    (boolean) $request->getPost('remember')
                );

                return $this->ajax->success();
            } catch (Exception $e) {
                return $this->ajax->error($e->getMessage());
            }
        }

        $this->assets->addCss('css/pages/login.css');

        // 禁用页面布局
        $this->view->disableHeader    = true;
        $this->view->disableContainer = true;
        $this->view->disableFooter    = true;

        // 禁用 controller 布局视图
        $this->view->disableLevel(Phalcon\Mvc\View::LEVEL_LAYOUT);

        $this->view->setVars(array(
            'bodyClass' => 'login',
            'requireJS' => 'login',
        ));

        prepend_title(__('User Login'));
    }

    public function logoutAction()
    {
        $this->auth->logout();

        return $this->redirect('user/login');
    }

    public function forgetAction()
    {
        return $this->ajax->error('功能尚未完成！');
    }

    public function resetAction()
    {
        return $this->ajax->error('功能尚未完成！');
    }

    public function listAction()
    {
        $request = $this->request;

        $filter = array_map('trim', array(
            'nickname'      => $request->getQuery('nickname'),
            'email'         => $request->getQuery('email'),
            'reg_time_from' => $request->getQuery('reg_time_from'),
            'reg_time_to'   => $request->getQuery('reg_time_to'),
            'status'        => $request->getQuery('status'),
            'dept_id'       => $request->getQuery('dept_id'),
            'role_id'       => $request->getQuery('role_id'),
        ));

        $builder = OaUsers::getFilterBuilder($filter)->orderBy('OaUsers.user_id desc');

        $paginator = new Paginator(array(
            'builder' => $builder,
            'limit'   => 20,
            'page'    => $request->getQuery('page', 'int', 1),
        ));

        $this->view->filter      = $filter;
        $this->view->page        = $paginator->getPaginate();
        $this->view->roles       = OaRoles::getAll();
        $this->view->departments = OaDepartments::getAll();
    }

    public function statusAction($user_id = 0)
    {
        return $this->ajax->error('功能尚未完成！');
    }

    public function createAction()
    {
        $this->flash->error('功能尚未完成！');
    }

    public function editAction()
    {
        $this->flash->error('功能尚未完成！');
    }

}
